 /*
  * Copyright (C) 2005 Wim Dumon
  *
  * See the LICENSE file for terms of use.
  */

 #include <Wt/WText>
 #include <Wt/WLabel>
 #include <Wt/WLineEdit>
 #include <Wt/WBreak>
 #include <Wt/WCssDecorationStyle>
 #include <Wt/WPushButton>
 #include <Wt/WTable>
 #include <Wt/WTableCell>
 #include <Wt/WComboBox>
 #include <Wt/WString>
 #include <Wt/WWidget>
 #include <QString>

 #include "LoginWidget.h"
#include "CommonWidget.h"

#include "DbSession.h"


 LoginWidget::LoginWidget(WContainerWidget *parent):
    WContainerWidget(parent)
    {

                           // application title
       addWidget(new WText("<p>This is a system for fans of healthy lifestyle. "
                   "You can fix your diet/activity program, and compare "
                   "with other users. But system needs to know your  "
                   "login, to work with your personal information</p>"));

      layout = new WTable();
      addWidget(layout);
      WLabel *usernameLabel = new WLabel("User name: ", layout->elementAt(0, 0));
      layout->elementAt(0, 0)->resize(WLength(13, WLength::FontEx), WLength::Auto);
      Username = new WLineEdit(layout->elementAt(0, 1));
      Username->focussed().connect(this, &LoginWidget::cleanGreeting);
      usernameLabel->setBuddy(Username);
      Username->setFocus();

      WLabel *passwordLabel = new WLabel("Password: ", layout->elementAt(1, 0));
      Password = new WLineEdit(layout->elementAt(1, 1));
      Password->setMargin(5, Top);
      Password->setEchoMode(WLineEdit::Password);
      passwordLabel->setBuddy(Password);

      addWidget(new WBreak());                       // insert a line break
      WPushButton *logBtn = new WPushButton("Log me IN", layout->elementAt(3, 1)); // create a button
      logBtn->setMargin(10,Right);
      logBtn->setMargin(5, Top);
      WPushButton *regModeBtn = new WPushButton("Add new account", layout->elementAt(3, 1));

      addWidget(Message = new WText());

      logBtn->clicked().connect(this, &LoginWidget::login);
      Password->enterPressed().connect(boost::bind(&LoginWidget::login, this));
      regModeBtn->clicked().connect(this, &LoginWidget::registrationMode);
      layout->elementAt(4,1)->show();
}

 LoginWidget::~LoginWidget()
 {
     delete layout;
     delete Message;
 }

    void LoginWidget::cleanGreeting(){
       Message->setText("");
    }

    void LoginWidget::loginMode(){
       layout->elementAt(2,0)->hide();
       layout->elementAt(2,1)->hide();
       layout->elementAt(4,1)->hide();
       layout->elementAt(3,1)->show();

       Message->setText("");
       Username->setText("");
       Password->setText("");
       ConfirmPassword->setText("");
    }

    void LoginWidget::login()
    {
      //check login and password
      if (Username->text().empty()==false)
      {
         if (Password->text().empty()==false)
         {
            int res = DbSession::getInstance().login(QString(Username->text().toUTF8().c_str()),
                            QString(Password->text().toUTF8().c_str()));

            if (res!=0)
            {

               loginSuccessful(res);
            }
            else
            {
               Password->setText("");
               Message->setText("Wrong password");
            }
         }
         else
         {
            Message->setText("Password can't be empty");
         }
       }
      else
      {
        Message->setText("Username can't be empty");
      }
    }

    void LoginWidget::registrationMode(){
        layout->elementAt(3,1)->hide();

        if (layout->elementAt(4,1)->isHidden()){
            layout->elementAt(4,1)->setHidden(false);
            layout->elementAt(2,0)->show();
            layout->elementAt(2,1)->show();
        }
        else
        {
          new WLabel ("Confirm password:",layout->elementAt(2,0));
          ConfirmPassword = new WLineEdit(layout->elementAt(2,1));
          ConfirmPassword->setEchoMode(WLineEdit::Password);
          ConfirmPassword->setMargin(5, Top);
          ConfirmPassword->enterPressed().connect(boost::bind(&LoginWidget::addUser, this));

          WPushButton *regBtn= new WPushButton("Register", layout->elementAt(4, 1));
          regBtn->clicked().connect(this, &LoginWidget::addUser);
          regBtn->setMargin(5, Top);

          WPushButton *cancBtn= new WPushButton("Cancel", layout->elementAt(4, 1));
          cancBtn->clicked().connect(this, &LoginWidget::loginMode);
        }
        Message->setText("");
    }

    void LoginWidget::addUser(){
      if (Username->text().empty()==false)
      {
       if (DbSession::getInstance().isFreeLogin(QString(Username->text().toUTF8().c_str())))
       {
               if (Password->text().empty()==false)
               {
                 if (Password->text().operator ==(ConfirmPassword->text()))
                {
                   if (DbSession::getInstance().registerUser
                          (QString(Username->text().toUTF8().c_str()),
                          QString(Password->text().toUTF8().c_str())))
                   {
                       /* We should set initial information about user */
                       int userId = DbSession::getInstance().login(QString(Username->text().toUTF8().c_str()),
                                                               QString(Password->text().toUTF8().c_str()));
                       DbSession::getInstance().addDietPlan(userId,
                           "Your diet plan is still empty. Go ahead and do it!");
                       DbSession::getInstance().addFitnessPlan(userId,
                           "Your fitness plan is still empty. Go ahead and do it!");

                      login();
                   }
                   else
                   {
                       Message->setText("Sorry. User can not be added");
                   }
                }
                 else
              {
                 Password->setText("");
                 ConfirmPassword->setText("");
                 Message->setText("Passwords are not equal");
              }
               }
               else
               {
                  Password->setText("");
                  ConfirmPassword->setText("");
                  Message->setText("Password can't be empty");
               }
       }
       else
       {
          Username->setText("");
          Password->setText("");
          ConfirmPassword->setText("");
          Message->setText("Such login name already exists. Please,select another one.");
       }
      }
      else
      {
          Message->setText("Username can't be empty");
      }
    }
